package com.example.birdfriends.controller;

import com.example.birdfriends.utils.mail.MailService;
import com.example.birdfriends.pojo.user.User;
import com.example.birdfriends.pojo.user.UserForm;
import com.example.birdfriends.service.UserService;
import com.example.birdfriends.utils.verifyCode.VerificationCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private MailService mailService = null;
    @Autowired
    private UserService userService = null;

    @PostMapping("/code")  // 获取验证码
    public Map<String, Object> getEMail(@RequestBody UserForm userEmail, HttpSession session){
        String email = userEmail.getEmail();
//        userEmail.print();
        mailService.sendMineMail(email, session);

        return resultMap(email != null, email, null);
    }

    @PostMapping("/register")
    @ResponseBody
    public Map<String, Object> register(@RequestBody UserForm user, HttpSession session){  // 接受表单的数据不需要@RequestBody
        Map<String, Object> verifyResult = userService.verifyRegister(user, session);
        User user1 = null;
        if((boolean)verifyResult.get("success")){
            // 再次验证用户的是否已注册
            if(userService.isExist(user)){  // 用户已存在
                Map<String, Object> map = new HashMap<>();
                map.put("success", false);
                map.put("msg", "注册失败，用户已存在");
                map.put("obj", user);
                return map;
            }
            // 验证成功，添加用户到数据库
            user1 = new User();
            user1.setEmail(user.getEmail());
            user1.setPassword(user.getPassword());
            user1.setNickname(user.getUserName());
            if(user1.getNickname() == null || user1.getNickname().isEmpty()) {
                StringBuilder nicknameSuffix = new StringBuilder();
                for (int i = 0; i < 7; i++) {
                    nicknameSuffix.append(new Random().nextInt(9));
                }
                // 产生自定义用户的系统名
                String nickname = "鸟友" + nicknameSuffix;
                user1.setNickname(nickname);
            }
            System.out.print("打印user:");user1.printUser();
            int ans = userService.insertUser(user1);
            boolean success = ans > 0;
            if (success){
                return resultMap(true, "注册成功", user1);
            }
            return resultMap(false, "注册失败", null);
        }

        return resultMap(false, (String) verifyResult.get("message"), null);
    }

    @GetMapping("/verifyCode/{time}")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response, @PathVariable("time") Date time) throws IOException {
        System.out.println(time);
        VerificationCode code = new VerificationCode();
        BufferedImage image = code.getImage();  // 前端验证码图片
        String text = code.getText();
        HttpSession session = request.getSession(true);  // 将验证码放入session
        session.setAttribute("verify_code", text);
        VerificationCode.output(image, response.getOutputStream());
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody UserForm user, HttpSession session){
        Map<String, Object> verifyLogin = userService.verifyLogin(user, session);
        boolean verify = (boolean)verifyLogin.get("success");
        if(!verify){
            // 验证码验证不通过
            return resultMap(false, (String) verifyLogin.get("message"), null);
        }
        User user1 = userService.findUserByEmailAndPassword(user.getEmail(), user.getPassword());
        boolean success = user1 != null;
        if (success){
            user1.setPassword("");  // 将密码设置为空，防止用户从浏览器获取密码
            return resultMap(true, "登陆成功", user1);
        }

        return resultMap(false, "登陆失败, 邮箱或密码错误", null);
    }

    String avatarUrl;

    @PostMapping("/upload")  // 现有帖子才有pid，但是当前帖子还没有创建，所以pid不存在，甚至post其他信息基本不存在
    public String saveAvatar(MultipartFile file, Long uid) throws IOException {
//        System.out.println("保存头像");
        String originalFilename = file.getOriginalFilename();
//        String mainName = originalFilename.substring(0, originalFilename.indexOf("."));
        String extName = originalFilename.substring(originalFilename.indexOf(".")+1);
        String mainName = "user"+uid+"-avatar."+extName;

        String filePath = "D:/bf-files/springboot-upload/user-heads/user"+uid+"/";
        System.out.println(filePath);
        File parentPath = new File(filePath);

        // 判断父级文件夹是否存在
        if(!parentPath.exists()){
            // 如果当前文件的父目录存在，就创建父目录
            parentPath.mkdirs();
        }
        File saveFile = new File(filePath + mainName);
        file.transferTo(saveFile);  // 存储文件

        this.avatarUrl = "http://localhost:8888/user-heads/user"+uid+"/"+mainName;
        return this.avatarUrl;
    }

    // 用户编辑信息：不可以修改邮箱，密码
    @PostMapping("/edit")
    public Map<String, Object> editInfo(@RequestBody User user){
//        user.printUser();
        System.out.println(avatarUrl);
        // 检测有哪些属性为空，也就是用户没有填写的内容，密码肯定是无法在此修改的，所以password必定为空，遇到空的属性直接用旧数据覆盖
        if(user == null){
            return resultMap(false, "更新失败，更新数据为空", user);
        }
        String email = user.getEmail();  // 邮箱是每个用户特有的，所以可以通过邮箱查找
        User oldUser = userService.findUserByEmail(email);  // 数据库中的原始用户信息

        // user.setId(oldUser.getId());  // 用户id不需要变，表单传过来的用户肯定没有id项数据
        if((user.getNickname() != null || user.getNickname().length() > 0) && !user.getNickname().equals(oldUser.getNickname())){
            oldUser.setNickname(user.getNickname());
        }
        if((user.getPhone() != null || user.getPhone().length() > 0) && !user.getPhone().equals(oldUser.getPhone())){
            oldUser.setPhone(user.getPhone());
        }
        if(user.getBirthday() != null){
            oldUser.setBirthday(user.getBirthday());
        }
        if((user.getPlace() != null || user.getPlace().length() > 0) && !user.getPlace().equals(oldUser.getPlace())){
            oldUser.setPlace(user.getPlace());
        }
        if((user.getSex() != null || user.getSex().length() > 0) && !user.getSex().equals(oldUser.getSex())){
            oldUser.setSex(user.getSex());
        }
        if((user.getSign() != null || user.getSign().length() > 0) && !user.getSign().equals(oldUser.getSign())){
            oldUser.setSign(user.getSign());
        }
        if((user.getUrl() != null || user.getUrl().length() > 0) && !user.getUrl().equals(avatarUrl)){
            oldUser.setUrl(avatarUrl);
        }
        System.out.println("用户头像:"+oldUser.getUrl());
        // 更新用户信息
        int update = userService.updateUser(oldUser);

        return resultMap(update > 0, update > 0 ? "更新成功" : "更新失败", oldUser);
    }

    // 用户忘记密码，修改密码
    @PostMapping("/newPwd")  // 用户需要先获取验证码，最后同时提交验证码，新密码，确认密码
    public Map<String, Object> changPassword(@RequestBody UserForm userForm, HttpSession session){
        userForm.print();
        Map<String, Object> change = userService.verifyRegister(userForm, session);  // 验证验证码，密码，确认密码
        Map<String, Object> ans = new HashMap<>();
        if((boolean)change.get("success")){  // 修改成功
            String password = userForm.getPassword();
            String email = userForm.getEmail();
            int updatePassword = userService.updatePassword(password, email);
            ans.put("success", updatePassword > 0);
            ans.put("msg", updatePassword > 0 ? "修改成功" : "修改失败");
            ans.put("user", userService.findUserByEmailAndPassword(email, password));
        }

        return ans;
    }

    @PostMapping("/logoff")
    public Map<String, Object> logoff(@RequestBody User user){
        user.printUser();
        Long id = user.getId();
        int del = userService.logoff(id);
        return resultMap(del > 0, del>0?"删除成功":"删除失败", null);
    }

    @PostMapping("/info")
    public Map<String, Object> findUserInfo(@RequestBody User user){
        String email = user.getEmail();
        String password = user.getPassword();
        System.out.println(email + "  " + password);
        User oldUser = userService.findUserByEmailAndPassword(email, password);  // 数据库中的原始用户信息
        System.out.println("user from form:");
        user.printUser();
        System.out.println("user from database:");
        oldUser.printUser();

        return resultMap(true, user==null?"查询失败":"查询成功", oldUser);
    }

    private HashMap<String, Object> resultMap(boolean success, String msg, Object obj){
        HashMap<String, Object> ans = new HashMap<>();
        ans.put("success", success);
        ans.put("msg", msg);
        ans.put("obj", obj);

        return  ans;
    }
}


